﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Data;
using VAdvantage.DataBase;
using VAdvantage.Utility;
using System.Threading;
using System.ComponentModel;
using System.Collections;

namespace VAdvantage.Framework
{
    public partial class MarkModule : ChildWindow
    {
        string[] _recordID = null;
        string[] _recordID2 = null;
        string _strRecordID = "";
        string _strRecordID2 = "";
        int _tableID = 0;
        string _tableName = "";
        public bool isSaved = false;
        public MarkModule()
        {
            InitializeComponent();
            BindModule();
            isSaved = false;


        }
        public MarkModule(string recordID, int TableID, string tableName)
            : this()
        {

            _recordID = recordID.Split(',');
            _strRecordID = recordID;
            _tableID = TableID;
            _tableName = tableName;

        }

        public MarkModule(string recordID, string recordID2, int TableID, string tableName)
            : this()
        {
            _recordID2 = recordID2.Split(',');
            _recordID = recordID.Split(',');
            _strRecordID = recordID;
            _strRecordID2 = recordID2;
            _tableID = TableID;
            _tableName = tableName;
        }


        private void BindModule()
        {
            var list = new List<KeyValuePair<int, string>>();
            list.Add(new KeyValuePair<int, string>(0, "*"));
            DataSet ds = null;
            BackgroundWorker bgw = new BackgroundWorker();
            bgw.DoWork += (ov, ev) =>
                {

                    string sql = "SELECT AD_ModuleInfo_ID, Name FROM AD_Moduleinfo WHERE isActive='Y' ";

                    IDataReader dr = DB.ExecuteReader(sql);

                    while (dr.Read())
                    {

                        list.Add(new KeyValuePair<int, string>(int.Parse(dr["AD_ModuleInfo_ID"].ToString()), dr["Name"].ToString()));
                    }

                    dr.Close();

                    if (_recordID.Count() == 1)
                    {

                        sql = "select AD_moduleinfo_id " +

                              "from ad_exportdata e " +

                              "where e.record_id=" + _recordID[0] + " and e.ad_table_id=" + _tableID;


                        ds = DB.ExecuteDataset(sql, null);


                    }

                };

            bgw.RunWorkerCompleted += (ov, ev) =>
                {
                    bool isfound = false;
                    foreach (var elemant in list)
                    {

                        if (ds != null)
                        {
                            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                            {
                                if (Convert.ToString(elemant.Key) == "0" && Convert.ToString(ds.Tables[0].Rows[i][0]) == "")
                                {
                                    isfound = true;
                                    break;
                                }
                                else if (Convert.ToString(elemant.Key) == Convert.ToString(ds.Tables[0].Rows[i][0]))
                                {
                                    isfound = true;
                                    break;
                                }
                            }
                        }

                        chklstboxModule.AddItem(elemant, isfound);
                        isfound = false;
                    }

                };

            bgw.RunWorkerAsync();





        }
        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            string selectedID = chklstboxModule.GetSeletedIdsString();
            string seletedString = chklstboxModule.GetSelectedIDs();
            string[] moduleName = seletedString.Split(';');

            string[] moduleId = selectedID.Split(';');

            ArrayList result = new ArrayList();

            if (_recordID2 == null || _recordID2.Length == 0)
            {

                BackgroundWorker bgw = new BackgroundWorker();
                bgw.DoWork += (ov, ev) =>
                {
                    string sql = "delete from ad_exportdata where record_id in (" + _strRecordID + ") " +
                                    "and ad_table_id=" + _tableID;

                    try
                    {
                        int res = DB.ExecuteQuery(sql, null, null);
                    }
                    catch
                    {

                    }
                    for (int i = 0; i < moduleId.Count() - 1; i++)
                    {


                        for (int j = 0; j < _recordID.Count(); j++)
                        {
                            VAdvantage.Model.X_AD_ExportData obj = new Model.X_AD_ExportData(Envs.GetCtx(), 0, null);
                            obj.SetRecord_ID(int.Parse(_recordID[j].ToString()));
                            obj.SetAD_Table_ID(_tableID);
                            obj.SetAD_ModuleInfo_ID(int.Parse(moduleId[i]));

                            if (!obj.Save())
                            {
                                result.Add("RecordID->" + _recordID[j] + " for Module Name->" + moduleName[i] + ", is not marked");
                            }

                        }
                    }
                };

                bgw.RunWorkerCompleted += (ov, ev) =>
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();

                    for (int i = 0; i < result.Count; i++)
                    {
                        sb.Append(result[i].ToString() + Environment.NewLine);


                    }
                    if (sb.Length != 0)
                        VAdvantage.Classes.ShowMessage.Info(sb.ToString(), true, null, null);

                    this.DialogResult = true;
                    isSaved = true;
                };

                bgw.RunWorkerAsync();
            }
            else
            {
                BackgroundWorker bgw = new BackgroundWorker();
                bgw.DoWork += (ov, ev) =>
                {
                    string sql = "delete from ad_exportdata where record_id in (" + _strRecordID + ") and AD_ColOne_ID in (" + _strRecordID2 + ")" +
                                    "and ad_table_id=" + _tableID;

                    //String sql = "Select AD_ExportData_ID from AD_ExportData where Record_ID = " + Record_ID_1 + " AND AD_COLONE_ID = " + Record_ID_2 + " AND AD_Table_ID = " + Table_ID;

                    try
                    {
                        int res = DB.ExecuteQuery(sql, null, null);
                    }
                    catch
                    {

                    }

                    for (int i = 0; i < moduleId.Count() - 1; i++)
                    {


                        for (int j = 0; j < _recordID.Count(); j++)
                        {
                            VAdvantage.Model.X_AD_ExportData obj = new Model.X_AD_ExportData(Envs.GetCtx(), 0, null);
                            obj.SetRecord_ID(int.Parse(_recordID[j].ToString()));
                            obj.SetAD_Table_ID(_tableID);
                            obj.SetAD_ModuleInfo_ID(int.Parse(moduleId[i]));
                            obj.SetAD_ColOne_ID(int.Parse(_recordID2[j].ToString()));

                            if (!obj.Save())
                            {
                                result.Add("RecordID->" + _recordID[j] + "and RecordID2->" + _recordID2[j] + " for Module Name->" + moduleName[i] + ", is not marked");
                            }

                        }
                    }
                };

                bgw.RunWorkerCompleted += (ov, ev) =>
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();

                    for (int i = 0; i < result.Count; i++)
                    {
                        sb.Append(result[i].ToString() + Environment.NewLine);
                    }
                    if (sb.Length != 0)
                        VAdvantage.Classes.ShowMessage.Info(sb.ToString(), true, null, null);

                    this.DialogResult = true;
                    isSaved = true;
                };

                bgw.RunWorkerAsync();
            }
        }




        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
            isSaved = true;
        }

        private void chklstboxModule_Loaded(object sender, RoutedEventArgs e)
        {

        }

        public static bool IsMarked(int rec_id, int ad_table_id)
        {
            var list = new List<KeyValuePair<int, string>>();
            list.Add(new KeyValuePair<int, string>(0, "*"));
            DataSet ds = null;
            string sql = "SELECT AD_ModuleInfo_ID, Name FROM AD_Moduleinfo WHERE isActive='Y' and AD_Client_ID = " + Envs.GetContext().GetAD_Client_ID();

            IDataReader dr = DB.ExecuteReader(sql);

            while (dr.Read())
            {

                list.Add(new KeyValuePair<int, string>(int.Parse(dr["AD_ModuleInfo_ID"].ToString()), dr["Name"].ToString()));
            }

            dr.Close();


            sql = "select AD_moduleinfo_id " +

                     "from ad_exportdata e " +

                     "where e.record_id=" + rec_id + " and e.ad_table_id=" + ad_table_id + " and AD_Client_ID = " + Envs.GetContext().GetAD_Client_ID();


            ds = DB.ExecuteDataset(sql, null);
            bool isfound = false;
            foreach (var elemant in list)
            {

                if (ds != null)
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        if (Convert.ToString(elemant.Key) == "0" && Convert.ToString(ds.Tables[0].Rows[i][0]) == "")
                        {
                            isfound = true;
                            break;
                        }
                        else if (Convert.ToString(elemant.Key) == Convert.ToString(ds.Tables[0].Rows[i][0]))
                        {
                            isfound = true;
                            break;
                        }
                    }
                }
            }
            return isfound;

        }

        private void ChildWindow_Closing(object sender, CancelEventArgs e)
        {
            isSaved = true;
        }

    }
}

